package cn.springcloud.alibaba.security.handler;

import cn.springcloud.alibaba.core.base.BaseResponse;
import cn.springcloud.alibaba.core.base.Result;
import cn.springcloud.alibaba.core.util.RequestUtil;
import cn.springcloud.alibaba.core.util.ResponseUtil;
import cn.springcloud.alibaba.security.vo.UserInfo;
import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class MyLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
		String sessionId = request.getSession().getId();
		log.info("登录成功:{}", JSON.toJSONString(authentication));
		UserInfo principal = (UserInfo) authentication.getPrincipal();
		principal.setToken(sessionId);
		principal.setPassword(null);
		Result<UserInfo> result = new Result<>();
		result.setData(principal);
		ResponseUtil.outputJsonResponse(response, result);
	}
}
